package com.fzk.utils;

import java.nio.charset.StandardCharsets;

/**
 * 必须自定义hash实现，String的hashcode是存储地址，不够离散
 * @author fzk
 * @datetime 2023-03-17 17:06
 */
public class MyHash {
    /**
     * 这个hash实现好像还不错的捏
     *
     * @param val 字符串
     * @return 32位hash
     * @author fzk
     */
    public static int hash(String val) {
        byte[] bytes = val.getBytes(StandardCharsets.UTF_8);
        int len = bytes.length;
        int result = 0;
        for (int i = 0; i < len; i++) {
            int v = bytes[i];
            switch (i % 4) {
                case 0:
                    break;
                case 1:
                    v = v << 8;
                    break;
                case 2:
                    v = v << 16;
                    break;
                case 3:
                    v = v << 24;
                    break;
            }
            result = result ^ v;
        }
        result = result ^ (result >>> 16);// 高16位与低16位异或
        if (result<0) result=-result;// 取正数
        return result;
    }
}
